package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import com.sun.org.apache.regexp.internal.RE;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.util.Map;

//进店客户
@RestController
@Slf4j
public class UserController {

    @Autowired
    private HttpSession httpSession;

    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private HttpSession session;

    //发送短信验证码
    @PostMapping("/user/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map<String, String> map) {
        //1. 接收参数
        String phone = map.get("phone");

        //2.生成验证码
        //String code = RandomUtil.randomNumbers(6);
        //todo 写死一个验证码为123 为了测试方便
        String code = "123";
        log.info("生成的验证码为:{}", code);

        //3. 将验证码保存到session中
        httpSession.setAttribute("SMS_" + phone, code);

        //4. 发送验证码到手机
        //smsTemplate.sendSms(phone, code);

        return ResultInfo.success(null);
    }

    //用户登录注册
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        //1. 接收参数
        String phone = map.get("phone");
        String code = map.get("code");

        //2. 校验code  前端传入code  VS  session保存code
        String codeFromSession = (String) httpSession.getAttribute("SMS_" + phone);
        if (!StringUtils.equals(code, codeFromSession)
                || StringUtils.isEmpty(code)
                || StringUtils.isEmpty(codeFromSession)) {
            return ResultInfo.error("验证码不对");
        }

        //3. 根据phone从数据库查询
        User user = userService.findByPhone(phone);
        if (user != null) {
            //3-1 查到了,代表的是老用户在登录
        } else {
            //3-2 没查到,代表新用户在注册
            user = new User();

            user.setPhone(phone);
            user.setStatus(1);//激活
            userService.save(user);
        }

        //4. 将user信息保存到session中(注意: 这个键必须跟拦截器中使用的键一致)
        httpSession.setAttribute("SESSION_USER", user);

        //5. 返回成功标识(注意不要忘记返回user,前端要用)
        return ResultInfo.success(user);
    }
    @PostMapping("user/logout")
    public ResultInfo logOut(){
        //1. 注销当前用户的session
        session.invalidate();//注销的当前用户的session,不会动的其它session

        //2. 返回成功标识
        return ResultInfo.success(null);
    }
}